"use strict";

import React from 'react';
import ReactDOM from 'react-dom';
import {
  Step,
  Stepper,
  StepLabel,
  StepContent,
} from 'material-ui/Stepper';
import RaisedButton from 'material-ui/RaisedButton';
import Subheader from 'material-ui/Subheader';
import TextField from 'material-ui/TextField';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
import RaUtil from './RaUtil.js';
import Truedata from 'truedata-js';
const truedata = new Truedata.Api();

// 补录 sd name, 库名, 代码型 code
const AMEND_RECORED_RULE = 'AmendRecoredRule',
      METADATA_STORE_CODE = 'metadata_origin',
      DATA_STANDARD_STORE_CODE = 'data_standard',
      DATA_TYPE_CODE = 'data_type_member_07',
      STANDARD_CODE_PROP_NAME = 'codeRange';
// 依赖 SD name
const DEPEND_SD_NAMES = {
    DATA_STANDARD: 'DataStandardBasic',
    BUSINESS_SYSTEM: 'BusinessSystem',
    DATA_SOURCE:'DataSource',
    SCHEMA: 'Schema',
    METADATA_TABLE: 'MetadataTable',
    METADATA_FIELD:'MetadataField'
};
// 补录属性名称
const AMEND_RECORED_PROPS = {
    NAME:'name',
    DESC: 'desc',
    IMPORTANCE: 'importance',
    MEASURE_DIMENSIONS:'measureDimensions',
    MEASURE_DIMENSIONS_CONTENT: 'measureDimensionsContent',
    DATA_STANDARD: 'dataStandard',
    BUSINESS_SYSTEM: 'businessSystem',
    DATA_SOURCE: 'dataSource',
    SCHEMA: 'schema',
    MATADATA_TABLE:'metadataTable',
    METADATA_FIELD:'metadataField',
    NEED_FEEDBACK: 'needFeedback',
    AMEND_RECORED: 'amendRecord',
    CHECK_SQL: 'checkSql',
    MAPPING_RULES: 'mappingRules'
};
// 版本查询
const gragitMetadata = truedata.createGragit(METADATA_STORE_CODE),
      gragitStandard = truedata.createGragit(DATA_STANDARD_STORE_CODE);
// select 默认选项
const SELECT_DEFAULT = {
    LABEL: '--请选择--',
    VALUE: ''
};
// 消息提示类型
const MSG_TYPE = {
    INFO: 'info',
    ERROR: 'error'
};
// 当前正在查询
let querying_prop_names = [];
// 样式
const styles = {
    table: {
        width: '100%'
    },
    tableTr: {
        lineHeight: '24px'
    },
    tableTh: {
        fontSize: '12px',
        textAlign: 'left',
        borderBottom: '1px solid #eee'
    },
    tableTd: {
        fontSize: '12px',
        borderBottom: '1px solid #eee',
        padding: '5px'
    },
    checkSqlTip: {
        fontSize: '12px',
        lineHeight: '24px',
        color: '#757575'
    },
    checkSqlDemo: {
        backgroundColor: '#EEEEEE',
        color: '#424242',
        border: '1px solid #BDBDBD',
        padding: '10px',
        borderRadius: '10px'
    }
};
// 补录映射值
const FIELD_ALIAS_RANGE = [
    {"key": "F_CHECK", "value": "检查字段"},
    {"key": "F_ID", "value": "唯一标识"},
    {"key": "F_BRC", "value": "机构编号"},
    {"key": "F_SUB", "value": "辅助标识"},
    {"key": "F_TRANDATE", "value": "开立时间"},
    {"key": "F_TELLER", "value": "操作员"}
];
const test_code_values = [
    {"__id":1,"__sd":"Signifier","notation": "test1","title":"测试1","isGeneral": false},
    {"__id":2,"__sd":"Signifier","notation": "test2","title":"测试2","isGeneral": false},
    {"__id":3,"__sd":"Signifier","notation": "test3","title":"测试3","isGeneral": false},
    {"__id":4,"__sd":"Signifier","notation": "test4","title":"测试4","isGeneral": false},
    {"__id":5,"__sd":"Signifier","notation": "test5","title":"测试5","isGeneral": false}
];
let test_field_values = [
    {"__id":6,"__sd": "MetadataFieldValue","fieldId": 1,"fieldValue": "test6","title": "字段6"},
    {"__id":7,"__sd": "MetadataFieldValue","fieldId": 1,"fieldValue": "test7","title": "字段7"},
    {"__id":8,"__sd": "MetadataFieldValue","fieldId": 1,"fieldValue": "test8","title": "字段8"},
    {"__id":9,"__sd": "MetadataFieldValue","fieldId": 1,"fieldValue": "test9","title": "字段9"}
];
// 定时刷新
let REFRESH_INTERVAL;
class RaAmendRecordEditor extends React.Component {
    constructor(props) {
        super(props);
		this.state = {
            raReady : props.raReady,
            ra: props.raReady.ra,
            data: props.raReady.data,
            amendRecordRule: {},
            amendRecordRuleText: {},
            propValid: {},
            propHtml: {},
            valueMappingHtml: [],     // 值映射
            aliasMappingHtml: [],     // 别名映射
            checkResultHtml:[],       // 结果预览
            stepIndex: 0,
            stepFinished: false,
            standardData: [],        // 数据标准
            standardCode: '',        // 标准编码
            metadataFieldName: '',   // 元数据字段名称
            fieldValues: [],         // 字段取值范围
            codeValues:[],            // 代码取值范围
            fieldAndCodeMapping: [],  // 字段和代码映射
            fieldAndAliasMapping:[],  // 字段和别名映射
            amendRecordCondition:[],
            selectFieldsResult:[],
            checkSqlResult:{"fields":["testA","testB"],"datas":[{"testA":1,"testB":1},{"testA":2,"testB":2}]}
		};
        // 映射
        this.selectedMapping = this.selectedMapping.bind(this);
	}
    // 根据属性还原相关属性
    restoreHtmlByProp(propName){
        // TODO
    }
    // 选中数据
    selectedValue(propName,propValue){
        let _amendRecordRule = this.state.amendRecordRule,
            _amendRecordRuleText = this.state.amendRecordRuleText,
            _propValid = this.state.propValid,
            _curLabel = event.target.innerText;
        if(!_amendRecordRule)_amendRecordRule = {};
        switch (propName) {
            case AMEND_RECORED_PROPS.MEASURE_DIMENSIONS:
                _amendRecordRule[AMEND_RECORED_PROPS.MEASURE_DIMENSIONS_CONTENT] = '';
                break;
            case AMEND_RECORED_PROPS.DATA_STANDARD:
                // 设置数据标准代码取值范围类
                let _standardCode = '';
                for(let curStandard of this.state.standardData){
                    if(curStandard['__id'] == propValue){
                        _standardCode = curStandard[STANDARD_CODE_PROP_NAME];
                        break;
                    }
                }
                if(_standardCode){
                    this.setState({'standardCode': _standardCode});
                }
                break;
            default:
        }
        if(typeof propValue != 'undefined' && propValue != ''){
            _propValid[propName] = '';
            _amendRecordRuleText[propName] = _curLabel;
        }else{
            delete _amendRecordRuleText[propName];
        }
        _amendRecordRule[propName] = propValue;
        // 根据属性还原相关属性
        this.restoreHtmlByProp(propName);
        this.setState({'amendRecordRule': _amendRecordRule,'amendRecordRuleText': _amendRecordRuleText});
    }
    // 生成下拉选项
    generateOptions(propName,nodeSd,nodeData){
        let itemHtml = [];
        // 默认选项
        itemHtml.push(<MenuItem value={SELECT_DEFAULT.VALUE}
                                primaryText={SELECT_DEFAULT.LABEL}
                                onClick={this.selectedValue.bind(this,propName,'')}/>);
        // display 属性
        let displayProp = nodeSd['display'];
        for(let i = 0; i < nodeData.length; i++){
            let _curOption = nodeData[i],
                _curKey = parseInt(_curOption['__id'],10),
                _curValue = '';
            for(let curProp of displayProp){
                _curValue += _curOption[curProp]?_curOption[curProp]:'';
            }
            if(!_curValue){
                _curValue = _curOption['__id'];
            }
            itemHtml.push(<MenuItem
                                value={_curKey}
                                primaryText={_curValue}
                                onClick={this.selectedValue.bind(this,propName,_curKey)}/>);
        }
        this.state.propHtml[propName] = itemHtml;
    }
    // 根据查询生成下拉框选项
    generateSelectByQuery(propName){
        if(this.state.propHtml[propName] || querying_prop_names.indexOf(propName) > -1)return;
        // 默认选数据查询
        let _gragit = gragitMetadata,
            _queryOption = {},
            _queryNodeName,
            _nodeName,
            _amendRecordRule = this.state.amendRecordRule;
        switch (propName) {
            case AMEND_RECORED_PROPS.DATA_STANDARD:
                _gragit = gragitStandard;
                _queryNodeName = _nodeName = DEPEND_SD_NAMES.DATA_STANDARD;
                // 只获取代码型标准
                _queryOption.params = {
                    'dataType': DATA_TYPE_CODE
                };
                break;
            case AMEND_RECORED_PROPS.DATA_SOURCE:
                _queryNodeName = _nodeName = DEPEND_SD_NAMES.DATA_SOURCE;
                break;
            case AMEND_RECORED_PROPS.SCHEMA:
                _queryNodeName = DEPEND_SD_NAMES.DATA_SOURCE;
                _nodeName = DEPEND_SD_NAMES.SCHEMA;
                _queryOption.chains = [`${_queryNodeName}<BELONG_TO-${_nodeName}`];
                _queryOption.params = {
                    "__id": _amendRecordRule[AMEND_RECORED_PROPS.DATA_SOURCE]
                };
                break;
            case AMEND_RECORED_PROPS.METADATA_TABLE:
                _queryNodeName = DEPEND_SD_NAMES.SCHEMA;
                _nodeName = DEPEND_SD_NAMES.METADATA_TABLE;
                _queryOption.chains = [`${_queryNodeName}<BELONG_TO-${_nodeName}`];
                _queryOption.params = {
                    "__id": _amendRecordRule[AMEND_RECORED_PROPS.SCHEMA]
                };
                break;
            case AMEND_RECORED_PROPS.METADATA_FIELD:
                _queryNodeName = DEPEND_SD_NAMES.METADATA_TABLE;
                _nodeName = DEPEND_SD_NAMES.METADATA_FIELD;
                _queryOption.chains = [`${_queryNodeName}<BELONG_TO-${_nodeName}`];
                _queryOption.params = {
                    "__id": _amendRecordRule[AMEND_RECORED_PROPS.METADATA_TABLE]
                };
                break;
            default:
        }
        _queryOption.nodeName = _queryNodeName;
        _queryOption.exact = true;
        _queryOption.attachRelation = false;
        _queryOption.attachRelationData = false;
        querying_prop_names.push(propName);
        // 查询
        _gragit.query(
        	_queryOption,
        	(err,result)=>{
                if(err){
                    this.state.ra.openMessage(err.message,MSG_TYPE.ERROR);
                    return;
                }
                let nodeSd = result.data.sd.node.impl[_nodeName],
                    resultData = result.data.data.node,
                    nodeData = [];
                for(let curNode of resultData){
                    if(curNode['__sd'] == _nodeName){
                        nodeData.push(curNode);
                    }
                }
                // 记录数据标准数据
                if(propName == AMEND_RECORED_PROPS.DATA_STANDARD){
                    this.setState({'standardData': nodeData});
                }
                this.generateOptions(propName,nodeSd,nodeData);
                // 完成后从查询中移除
                querying_prop_names.splice(querying_prop_names.indexOf(propName),1);
            });
    }
    // 下拉框选项
    generateSelectItems(propName){
        let itemHtml = [];
        // 默认选项
        itemHtml.push(<MenuItem value={SELECT_DEFAULT.VALUE}
                                primaryText={SELECT_DEFAULT.LABEL}
                                onClick={this.selectedValue.bind(this,propName,'')}/>);
        // 下拉选项
        let optionData = this.state.data.sd.node.impl[AMEND_RECORED_RULE].prop[propName];
        for(let i = 0; i < optionData.valueSource.length; i++){
            let _curOption = optionData.valueSource[i];
            // 维度内容
            if(propName == AMEND_RECORED_PROPS.MEASURE_DIMENSIONS_CONTENT){
                if(!this.state.amendRecordRule || !this.state.amendRecordRule[AMEND_RECORED_PROPS.MEASURE_DIMENSIONS])break;
                if(_curOption.parent != this.state.amendRecordRule[AMEND_RECORED_PROPS.MEASURE_DIMENSIONS]){
                    continue;
                }
            }
            let _curKey = _curOption.key,
                _curValue = _curOption.value;
            itemHtml.push(<MenuItem
                                value={_curKey}
                                primaryText={_curValue}
                                onClick={this.selectedValue.bind(this,propName,_curKey)}/>);
        }
        return itemHtml;
    }
    // 补充表单
    fillText(event){
        let _curId = event.target.getAttribute('id'),
            _value = event.target.value,
            _amendRecordRule = this.state.amendRecordRule,
            _propValid = this.state.propValid;
        _amendRecordRule[_curId] = _value;
        // 清空验证信息
        if(typeof _value != 'undefined' && _value != ''){
            _propValid[_curId] = '';
        }
        this.setState({'amendRecordRule':_amendRecordRule,'propValid': _propValid});
    }
    // 基础信息
    generateBasicStepHtml(){
        // 当前对象
        let amendRecordRule = this.state.amendRecordRule;
        let basicStepForm = [];
        // 规则名称
        let _nameKey = AMEND_RECORED_PROPS.NAME,
            _nameLabel = '规则名称',
            _nameValue = (amendRecordRule[_nameKey])?amendRecordRule[_nameKey]:'';
        basicStepForm.push(<TextField
                            id={_nameKey}
                            floatingLabelText={_nameLabel}
                            floatingLabelFixed={true}
                            value={_nameValue}
                            errorText={this.state.propValid[_nameKey]?this.state.propValid[_nameKey]:''}
                            onChange={this.fillText.bind(this)}/>);
        basicStepForm.push(<br/>);
        // 规则描述
        let _descKey = AMEND_RECORED_PROPS.DESC,
            _descLabel = '规则描述',
            _descValue = (amendRecordRule[_descKey])?amendRecordRule[_descKey]:'';
        basicStepForm.push(<TextField
                            id={_descKey}
                            floatingLabelText={_descLabel}
                            floatingLabelFixed={true}
                            value={_descValue}
                            errorText={this.state.propValid[_descKey]?this.state.propValid[_descKey]:''}
                            rows={5}
                            multiLine={true}
                            onChange={this.fillText.bind(this)}/>);
        basicStepForm.push(<br/>);
        // 重要程度
        let _importanceKey = AMEND_RECORED_PROPS.IMPORTANCE,
            _importanceLabel = '重要程度',
            _importanceValue = (amendRecordRule[_importanceKey])?amendRecordRule[_importanceKey]:'',
            _importanceItems = this.generateSelectItems(_importanceKey);
        basicStepForm.push(<SelectField
                                key={_importanceKey}
                                floatingLabelText={_importanceLabel}
                                floatingLabelFixed={true}
                                title={'请下拉选择'+_importanceLabel}
                                value={_importanceValue}
                                errorText={this.state.propValid[_importanceKey]?this.state.propValid[_importanceKey]:''}>
                                {_importanceItems}
                            </SelectField>);
        basicStepForm.push(<br/>);
        // 衡量维度
        let _measureDimensionsKey = AMEND_RECORED_PROPS.MEASURE_DIMENSIONS,
            _measureDimensionsLabel = '衡量维度',
            _measureDimensionsValue = (amendRecordRule[_measureDimensionsKey])?amendRecordRule[_measureDimensionsKey]:'',
            _measureDimensionsItems = this.generateSelectItems(_measureDimensionsKey);
        basicStepForm.push(<SelectField
                                key={_measureDimensionsKey}
                                floatingLabelText={_measureDimensionsLabel}
                                floatingLabelFixed={true}
                                title={'请下拉选择'+_measureDimensionsLabel}
                                value={_measureDimensionsValue}
                                errorText={this.state.propValid[_measureDimensionsKey]?this.state.propValid[_measureDimensionsKey]:''}>
                                {_measureDimensionsItems}
                            </SelectField>);
        basicStepForm.push(<br/>);
        // 衡量内容
        let _dimensionsContentKey = AMEND_RECORED_PROPS.MEASURE_DIMENSIONS_CONTENT,
            _dimensionsContentLabel = '衡量维度内容',
            _dimensionsContentValue = (amendRecordRule[_dimensionsContentKey])?amendRecordRule[_dimensionsContentKey]:'',
            _dimensionsContentItems = this.generateSelectItems(_dimensionsContentKey);
        basicStepForm.push(<SelectField
                                key={_dimensionsContentKey}
                                floatingLabelText={_dimensionsContentLabel}
                                floatingLabelFixed={true}
                                title={'请下拉选择'+_dimensionsContentLabel}
                                value={_dimensionsContentValue}
                                errorText={this.state.propValid[_dimensionsContentKey]?this.state.propValid[_dimensionsContentKey]:''}>
                                {_dimensionsContentItems}
                            </SelectField>);
        basicStepForm.push(<br/>);
        // 数据标准
        let _dataStandardKey = AMEND_RECORED_PROPS.DATA_STANDARD,
            _dataStandardLabel = '数据标准',
            _dataStandardValue = (amendRecordRule[_dataStandardKey])?amendRecordRule[_dataStandardKey]:'';
            this.generateSelectByQuery(_dataStandardKey);
        basicStepForm.push(<SelectField
                                key={_dataStandardKey}
                                floatingLabelText={_dataStandardLabel}
                                floatingLabelFixed={true}
                                title={'请下拉选择'+_dataStandardLabel}
                                value={_dataStandardValue}
                                errorText={this.state.propValid[_dataStandardKey]?this.state.propValid[_dataStandardKey]:''}>
                                {this.state.propHtml[_dataStandardKey]?this.state.propHtml[_dataStandardKey]:[]}
                            </SelectField>);
        basicStepForm.push(<br/>);
        // 下一步
        let currentProps = [_nameKey,_importanceKey,_measureDimensionsKey,_dimensionsContentKey,_dataStandardKey];
        basicStepForm.push(<RaisedButton label="下一步" primary={true} onClick={this.nextStep.bind(this,currentProps)}/>);
        return basicStepForm;
    }
    // 下一步
    nextStep(currentProps){
        let amendRecordRule = this.state.amendRecordRule,
            propValid = this.state.propValid,
            validFlag = true;
        // 当前属性
        for(let propName of currentProps){
            let propValue = amendRecordRule[propName];
            if(typeof propValue == 'undefined' || propValue == ''){
                validFlag = false;
                propValid[propName] = '必填';
            }
        }
        // 验证失败
        if(!validFlag){
            this.setState({'propValid': this.state.propValid});
        }else{
            // 验证成功，跳转至下一步
            let stepIndex = this.state.stepIndex;
            stepIndex += 1;
            this.setState({'stepIndex': stepIndex});
        }
    }
    // 动态Form
    generateDynamicStepHtml(propName){
        let dynamicStepForm = [],
            amendRecordRule = this.state.amendRecordRule;
        // 重要程度
        let _dynamicKey = propName,
            _dynamicLabel = '',
            _dynamicValue = (amendRecordRule[_dynamicKey])?amendRecordRule[_dynamicKey]:'';
        switch (propName) {
            case AMEND_RECORED_PROPS.DATA_SOURCE:
                _dynamicLabel = '数据源';
                if(amendRecordRule[AMEND_RECORED_PROPS.DATA_STANDARD]){
                    this.generateSelectByQuery(_dynamicKey);
                }
                break;
            case AMEND_RECORED_PROPS.SCHEMA:
                _dynamicLabel = '库';
                if(amendRecordRule[AMEND_RECORED_PROPS.DATA_SOURCE]){
                    this.generateSelectByQuery(_dynamicKey);
                }
                break;
            case AMEND_RECORED_PROPS.METADATA_TABLE:
                _dynamicLabel = '表';
                if(amendRecordRule[AMEND_RECORED_PROPS.SCHEMA]){
                    this.generateSelectByQuery(_dynamicKey);
                }
                break;
            case AMEND_RECORED_PROPS.METADATA_FIELD:
                _dynamicLabel = '字段';
                if(amendRecordRule[AMEND_RECORED_PROPS.METADATA_TABLE]){
                    this.generateSelectByQuery(_dynamicKey);
                }
                break;
            default:
        }
        dynamicStepForm.push(<SelectField
                                key={_dynamicKey}
                                floatingLabelText={_dynamicLabel}
                                floatingLabelFixed={true}
                                title={'请下拉选择'+_dynamicLabel}
                                value={_dynamicValue}
                                errorText={this.state.propValid[_dynamicKey]?this.state.propValid[_dynamicKey]:''}>
                                {this.state.propHtml[_dynamicKey]?this.state.propHtml[_dynamicKey]:[]}
                            </SelectField>);
        dynamicStepForm.push(<br/>);
        // 下一步
        let currentProps = [_dynamicKey];
        dynamicStepForm.push(<RaisedButton label="下一步" primary={true} onClick={this.nextStep.bind(this,currentProps)}/>);
        return dynamicStepForm;
    }
    // 查询映射值
    queryCodeAndFieldValue(){
        if(this.state.valueMappingHtml && this.state.valueMappingHtml.length)return;
        let _amendRecordRule = this.state.amendRecordRule;
        // 查询数据标准代码取值
        let _queryOption = {
                "nodeName": "Signifier",
                "params": {
                    "notation": this.state.standardCode
                },
                "chains": ["Signifier<QUOTE-DimensionSignifier<ASSOCIATED_WITH-DimensionSignifier-QUOTE>Signifier"],
                "attachRelation": false,
                "attachRelationData": false,
                "exact": true
        };
        truedata.uxdf.query(
        	_queryOption,
        	(err,signifierResult)=>{
                if(err){
                    this.state.ra.openMessage(err.message,MSG_TYPE.ERROR);
                    return;
                }
                console.log('signifierResult---------',signifierResult);
                this.setState({'codeValues': test_code_values});
                // 字段
                _queryOption = {
                    "nodeName": "MetadataFieldValue",
                    "params": {
                        "fieldId": this.state.amendRecordRule.metadataField
                    },
                    "attachRelation": false,
                    "attachRelationData": false,
                    "exact": true
                }
                gragitMetadata.query(
                        _queryOption,
                        (err,metadataResult)=>{
                            if(err){
                                this.state.ra.openMessage(err.message,MSG_TYPE.ERROR);
                                return;
                            }
                            console.log('metadataResult----------',metadataResult);
                            for(let curField of test_field_values){
                                curField.fieldId = this.state.amendRecordRule.metadataField;
                            }
                            this.setState({'fieldValues': test_field_values});
                            this.generateValueMapping();
                        }
                    );
        });
        console.log('standardCode-----------',this.state.standardCode);
        console.log('amendRecordRule--------',this.state.amendRecordRule.metadataField);
    }
    // 查询检查sql
    queryByCheckSql(){
        let propName = arguments[0],
            amendRecordRule = this.state.amendRecordRule,
            checkSql = amendRecordRule[propName];
        // TODO
        console.log('checkSql-------------',checkSql);
        // 生成别名映射
        this.generateAliasMapping();
        // 生成检查结果
        this.generateCheckResult();
        this.setState({stepIndex: 7});
    }
    // 选中映射
    selectedMapping(){
        let curField = arguments[0],
            curKey = arguments[1],
            curEvent = arguments[2],
            curCode = curEvent.target.value,
            mappingValues = [],
            _fieldInfo = curField + '-',
            _fieldIndex = -1;
        if(curKey == 'value'){
            mappingValues = this.state.fieldAndCodeMapping;
        }else if(curKey == 'alias'){
            mappingValues = this.state.fieldAndAliasMapping;
        }
        for(let i = 0; i < mappingValues.length; i++){
            let curMapping = mappingValues[i];
            if(curMapping.indexOf(_fieldInfo) > -1){
                _fieldIndex = i;
                break;
            }
        }
        // 清空上一次选择
        if(curCode == '' && _fieldIndex > -1){
            mappingValues.splice(_fieldIndex,1);
        }else if(curCode != ''){
            _fieldInfo += curCode;
            if(_fieldIndex > -1){
                mappingValues.splice(_fieldIndex,1,_fieldInfo);
            }else{
                mappingValues.push(_fieldInfo);
            }
        }
        if(curKey == 'value'){
            this.setState({'fieldAndCodeMapping': mappingValues});
            this.generateValueMapping();
        }else if(curKey == 'alias'){
            this.setState({'fieldAndAliasMapping': mappingValues});
            this.generateAliasMapping();
        }
    }
    // 生成取值映射
    generateValueMapping(){
        let mappingHtml = [],
            _fieldValues = this.state.fieldValues,
            _codeValues = this.state.codeValues,
            _fieldAndCodeMapping = this.state.fieldAndCodeMapping;
        // 字段取值范围一一映射
        for(let i = 0; i < _fieldValues.length; i++){
            let _mappingTrHtml = [],
                _curField = _fieldValues[i],
                _curFieldValue = _curField['__id'],
                _curFieldTitle = _curField.title;
            _mappingTrHtml.push(<td style={styles.tableTd}>{_curFieldTitle?_curFieldTitle:_curFieldValue}</td>);
            // 代码取值范围 -- 生成下拉框
            let _selectOption = [];
            _selectOption.push(<option value={SELECT_DEFAULT.VALUE}>{SELECT_DEFAULT.LABEL}</option>);
            for(let j = 0; j < _codeValues.length; j++){
                let _curCode = _codeValues[j],
                    _curCodeValue = _curCode['__id'],
                    _curCodeTitle = _curCode.title;
                let _mappingInfo = _curFieldValue+'-'+_curCodeValue,
                    _otherInfo = '-'+_curCodeValue,
                    _otherIndex = -1;
                for(let m = 0; m < _fieldAndCodeMapping.length; m++){
                    let _curMapping = _fieldAndCodeMapping[m];
                    if(_curMapping != _mappingInfo && _curMapping.indexOf(_otherInfo)> -1){
                        _otherIndex = m;
                        break;
                    }
                }
                if(_otherIndex != -1)continue;
                if(_fieldAndCodeMapping.indexOf(_mappingInfo) > -1){
                    _selectOption.push(<option value={_curCodeValue} selected>{_curCodeTitle}</option>);
                }else{
                    _selectOption.push(<option value={_curCodeValue}>{_curCodeTitle}</option>);
                }
            }
            _mappingTrHtml.push(<td style={styles.tableTd}><select onChange={this.selectedMapping.bind(this,_curFieldValue,'value')}>{_selectOption}</select></td>);
            mappingHtml.push(<tr style={styles.tableTr}>{_mappingTrHtml}</tr>);
        }
        this.setState({'valueMappingHtml': mappingHtml});
    }
    // 返回和别名映射
    generateAliasMapping(){
        let mappingHtml = [],
            _fieldValues = this.state.checkSqlResult.fields,
            _fieldAndAliasMapping = this.state.fieldAndAliasMapping;
        // 字段取值一一映射
        for(let i = 0; i < _fieldValues.length; i++){
            let _mappingTrHtml = [],
                _curField = _fieldValues[i];
            _mappingTrHtml.push(<td style={styles.tableTd}>{_curField}</td>);
            // 映射取值范围 -- 生成下拉框
            let _selectOption = [];
            _selectOption.push(<option value={SELECT_DEFAULT.VALUE}>{SELECT_DEFAULT.LABEL}</option>);
            for(let j = 0; j < FIELD_ALIAS_RANGE.length; j++){
                let _curAlias = FIELD_ALIAS_RANGE[j],
                    _curValue = _curAlias['key'],
                    _curTitle = _curAlias['value'];
                let _mappingInfo = _curField + '-' + _curValue,
                    _otherInfo = '-' + _curValue,
                    _otherIndex = -1;
                for(let m = 0; m < _fieldAndAliasMapping.length; m++){
                    let _curMapping = _fieldAndAliasMapping[m];
                    if(_curMapping != _mappingInfo && _curMapping.indexOf(_otherInfo)> -1){
                        _otherIndex = m;
                        break;
                    }
                }
                if(_otherIndex != -1)continue;
                if(_fieldAndAliasMapping.indexOf(_mappingInfo) > -1){
                    _selectOption.push(<option value={_curValue} selected>{_curTitle}</option>);
                }else{
                    _selectOption.push(<option value={_curValue}>{_curTitle}</option>);
                }
            }
            _mappingTrHtml.push(<td style={styles.tableTd}><select onChange={this.selectedMapping.bind(this,_curField,'alias')}>{_selectOption}</select></td>);
            mappingHtml.push(<tr style={styles.tableTr}>{_mappingTrHtml}</tr>);
        }
        this.setState({'aliasMappingHtml': mappingHtml});
    }
    // 生成检查结果
    generateCheckResult(){
        let checkSqlResult = this.state.checkSqlResult,
            _fieldValues = (checkSqlResult && checkSqlResult['fields'])?checkSqlResult['fields']:[],
            _checkResult = (checkSqlResult && checkSqlResult['datas'])?checkSqlResult['datas']:[],
            resultHtml = [];
        // 返回结果
        resultHtml.push(<Subheader>返回结果</Subheader>);
        let headHtml = [],headTrHtml = [];
        for(let curField of _fieldValues){
            headTrHtml.push(<th style={styles.tableTh}>{curField}</th>);
        }
        headHtml.push(<tr style={styles.tableTr}>{headTrHtml}</tr>);
        // 结果数据
        let bodyHtml = [];
        for(let curData of _checkResult){
            let bodyTrHtml = [];
            for(let curField of _fieldValues){
                let curInfo = curData[curField] != 'undefined' ? curData[curField] : '< null >';
                bodyTrHtml.push(<td style={styles.tableTd}>{curInfo}</td>);
            }
            bodyHtml.push(<tr style={styles.tableTr}>{bodyTrHtml}</tr>);
        }
        resultHtml.push(<table style={styles.table} cellspacing="0" cellpadding="0">
                            <thead>{headHtml}</thead>
                            <tbody>{bodyHtml}</tbody>
                        </table>);
        this.setState({'checkResultHtml': resultHtml});
    }
    // 代码取值映射
    generateValueMappingHtml(){
        if(!this.state.standardCode || !this.state.amendRecordRule.metadataField)return;
        let mappingHtml = [];
        this.queryCodeAndFieldValue();
        // 映射表
        mappingHtml.push(<div>
                             <table style={styles.table} cellspacing="0" cellpadding="0">
                                 <thead>
                                    <tr style={styles.tableTr}>
                                        <th style={styles.tableTh}>字段取值</th>
                                        <th style={styles.tableTh}>代码取值</th>
                                    </tr>
                                 </thead>
                                 <tbody>
                                    {this.state.valueMappingHtml}
                                 </tbody>
                             </table>
                             <br/>
                             <RaisedButton label="下一步" primary={true} onClick={() => this.setState({stepIndex: 6})}/>
                        </div>);
        return mappingHtml;
    }
    // 检查规则
    generateCheckStepHtml(){
        let checkFormHtml = [],
            amendRecordRule = this.state.amendRecordRule,
            amendRecordRuleText = this.state.amendRecordRuleText;
        // sql 脚本提示
        checkFormHtml.push(<div style={styles.checkSqlTip}>
                            <div>
                              检查脚本使用一个SQL查询语句，过滤出不符合检查标准的数据，以及部分必要的辅助信息作为数据补录参考。
                            </div>
                            <div>
                              查询语句必须返回“检查字段”、“唯一标识”、“机构编号”三个字段，可以额外返回“辅助标识”、“开立时间”、“操作员”三个字段。
                            </div>
                            <div>
                              返回的字段使用约定的别名标识，别名映射如下：
                            </div>
                            <ul>
                                  <li>检查字段*：F_CHECK</li>
                                  <li>唯一标识*：F_ID</li>
                                  <li>机构编号*：F_BRC</li>
                                  <li>辅助标识：F_SUB</li>
                                  <li>开立时间：F_TRANDATE</li>
                                  <li>操作员：F_TELLER</li>
                            </ul>
                            <div>
                                其中“唯一标识”和“辅助字段”可以返回多个，可以在别名后增加不同的后缀标识。比如：“F_ID_1”、“F_ID_2”，“F_SUB_1”、“F_SUB_2”
                            </div>
                            <div>
                                下面是一个语句示例：
                            </div>
                            <div style={styles.checkSqlDemo}>
                                SELECT uid AS F_ID, id_no AS F_ID_1, gender AS F_CHECK, org_id AS F_BRC, name AS F_SUB
                                    FROM user_info
                                    WHERE gender NOT IN ('1', '2')
                            </div>
                          </div>);
        // sql 检查脚本
        let _checkSqlKey = AMEND_RECORED_PROPS.CHECK_SQL,
            _checkSqlLabel = '检查脚本',
            _checkSqlValue = (amendRecordRule[_checkSqlKey])?amendRecordRule[_checkSqlKey]:'';
        if(!_checkSqlValue){
            let _curFieldText = amendRecordRuleText[AMEND_RECORED_PROPS.METADATA_FIELD],
                _curTableText = amendRecordRuleText[AMEND_RECORED_PROPS.METADATA_TABLE];
            _checkSqlValue = `select ${_curFieldText?_curFieldText:''}  as F_CHECK from ${_curTableText?_curTableText:''} `;
        }
        checkFormHtml.push(<TextField
                            id={_checkSqlKey}
                            floatingLabelText={_checkSqlLabel}
                            floatingLabelFixed={true}
                            value={_checkSqlValue}
                            errorText={this.state.propValid[_checkSqlKey]?this.state.propValid[_checkSqlKey]:''}
                            onChange={this.fillText.bind(this)}
                            rows={5}
                            multiLine={true}
                            fullWidth={true}/>);
        checkFormHtml.push(<br/>);
        checkFormHtml.push(<RaisedButton label="测试脚本" primary={true} onClick={this.queryByCheckSql.bind(this,_checkSqlKey)}/>);
        return checkFormHtml;
    }
    // 补录映射
    generateRecordMappingHtml(){
        let mappingHtml = [],
            amendRecordRule = this.state.amendRecordRule;
        // 检查返回
        mappingHtml.push(<table style={styles.table} cellspacing="0" cellpadding="0">
                            <thead>
                                <tr style={styles.tableTr}>
                                    <th style={styles.tableTh}>检查返回</th>
                                    <th style={styles.tableTh}>别名</th>
                                </tr>
                            </thead>
                            <tbody>
                                {this.state.aliasMappingHtml}
                            </tbody>
                         </table>);
        mappingHtml.push(<br/>);
        // 返回结果
        mappingHtml.push(<div>{this.state.checkResultHtml}</div>);
        mappingHtml.push(<br/>);
        // 是否自动补录
        let _amendRecordKey = AMEND_RECORED_PROPS.AMEND_RECORED,
            _amendRecordLabel = '是否自动补录',
            _amendRecordValue = (amendRecordRule[_amendRecordKey])?amendRecordRule[_amendRecordKey]:'',
            _amendRecordItems = this.generateSelectItems(_amendRecordKey);
        mappingHtml.push(<SelectField
                                key={_amendRecordKey}
                                floatingLabelText={_amendRecordLabel}
                                floatingLabelFixed={true}
                                title={'请下拉选择'+_amendRecordLabel}
                                value={_amendRecordValue}
                                errorText={this.state.propValid[_amendRecordKey]?this.state.propValid[_amendRecordKey]:''}>
                                {_amendRecordItems}
                            </SelectField>);
        mappingHtml.push(<br/>);
        // 补录映射
        return mappingHtml;
    }
    // 按步骤生成表单
    generateStepFormHtml(){
        let stepForms = [],
            activeStepIndex = this.state.stepIndex;
        // 基本信息
        let basicStepHtml = this.generateBasicStepHtml();
        stepForms.push(<Step>
                            <StepLabel onClick={() => this.setState({stepIndex: 0})}>
                                基本信息
                            </StepLabel>
                            <StepContent>
                                {basicStepHtml}
                            </StepContent>
                       </Step>);
        // 基本信息-数据源
        let dataSourceStepHtml = this.generateDynamicStepHtml(AMEND_RECORED_PROPS.DATA_SOURCE);
        stepForms.push(<Step>
                           <StepLabel onClick={() => this.setState({stepIndex: 1})}>
                               基本信息-数据源
                           </StepLabel>
                           <StepContent>
                               {dataSourceStepHtml}
                           </StepContent>
                      </Step>);
        // 基本信息-库
        let schemaStepHtml = this.generateDynamicStepHtml(AMEND_RECORED_PROPS.SCHEMA);
        stepForms.push(<Step>
                            <StepLabel onClick={() => this.setState({stepIndex: 2})}>
                                基本信息-库
                            </StepLabel>
                            <StepContent>
                                {schemaStepHtml}
                            </StepContent>
                       </Step>);
        // 基本信息-表
        let metadataTableStepHtml = this.generateDynamicStepHtml(AMEND_RECORED_PROPS.METADATA_TABLE);
        stepForms.push(<Step>
                           <StepLabel onClick={() => this.setState({stepIndex: 3})}>
                               基本信息-表
                           </StepLabel>
                           <StepContent>
                               {metadataTableStepHtml}
                           </StepContent>
                      </Step>);
        // 基本信息-字段
        let metadataFieldStepHtml = this.generateDynamicStepHtml(AMEND_RECORED_PROPS.METADATA_FIELD);
        stepForms.push(<Step>
                          <StepLabel onClick={() => this.setState({stepIndex: 4})}>
                              基本信息-字段
                          </StepLabel>
                          <StepContent>
                              {metadataFieldStepHtml}
                          </StepContent>
                     </Step>);
        // 基本信息-字段
        let valueMappingStepHtml = this.generateValueMappingHtml();
        stepForms.push(<Step>
                         <StepLabel onClick={() => this.setState({stepIndex: 5})}>
                             字段取值-代码取值映射
                         </StepLabel>
                         <StepContent>
                             {valueMappingStepHtml}
                         </StepContent>
                    </Step>);
        // 检查规则
        let checkRuleStepHtml = this.generateCheckStepHtml();
        stepForms.push(<Step>
                            <StepLabel onClick={() => this.setState({stepIndex: 6})}>
                                检查规则
                            </StepLabel>
                            <StepContent>
                                {checkRuleStepHtml}
                            </StepContent>
                       </Step>);
        // 补录映射
        let recoredMappingStepHtml = this.generateRecordMappingHtml();
        stepForms.push(<Step>
                           <StepLabel onClick={() => this.setState({stepIndex: 7})}>
                               补录映射
                           </StepLabel>
                           <StepContent>
                               {recoredMappingStepHtml}
                           </StepContent>
                      </Step>);
        return stepForms;
    }
    render() {
        let stepFormHtml = this.generateStepFormHtml();
		return (<div>
                    <Subheader>补录规则维护</Subheader>
                    <Stepper activeStep={this.state.stepIndex} orientation="vertical">
                        {stepFormHtml}
                    </Stepper>
                </div>);
	}
    // 挂载完成
    componentDidMount(){
        REFRESH_INTERVAL = setInterval(()=>{
            if(this.state.raReady.ra){
                if(!this.state.raReady.ra.openMessage){
                    this.state.raReady.ra.openMessage = function(msg,msgType){
                        console.log('msg--------',msg);
                        console.log('msfType----',msgType);
                    }
                }
                // 设置是否修改补录
                let _amendRecordRule,
                    _initData = this.state.raReady.data;
                if(_initData && _initData.node && _initData.node.length){
                    for(let curNode of _initData.node){
                        if(curNode['__sd'] == 'AmendRecordRule'){
                            _amendRecordRule = curNode;
                            break;
                        }
                    }
                }
                this.setState({ra: this.state.raReady.ra,
                               data: this.state.raReady.data,
                               amendRecordRule: _amendRecordRule?_amendRecordRule:{}});
                clearInterval(REFRESH_INTERVAL);
            }
        },300);
    }
}
export default RaAmendRecordEditor;
